<?php


namespace App\Http\Controllers\Backend1;

use App\Services\Business\Interfaces\CategoryServiceInterface;
use App\Services\Business\Models\Combo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Services\Business\Models\Category;
use App\Services\Business\Models\Course;
use App\Http\Requests\ApiV2\CategoryRequest;
use App\Events\CategoryUpdateEvent;


class CategoryController extends BaseController
{

    /**
     * @var CategoryServiceInterface
     */
    protected $categoryService;

    public function __construct(CategoryServiceInterface $categoryService)
    {
        $this->categoryService = $categoryService;
    }



    /**
     * 递归生成无限菜单树形结构
     *
     * @param array $items 菜单数组
     * @param int|null $parentId 父菜单ID
     * @return
     */

    public function tree(Request $request)
    {

        $categories = $this->categoryService->tree();
        return  $this->successData(compact('categories'));

    }


    public function store(CategoryRequest $request, Category $myCategory)
    {
        $myCategory->fill($request->filldata())->save();
        event(new CategoryUpdateEvent());
        return $this->success();

    }

    public function detail($id)
    {
        $category = Category::query()->where('id', $id)->firstOrFail();
        $categories = $category->children()->get()->toArray();

        return $this->successData(compact('category', 'categories'));
    }


    /**
     * @param CategoryRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(CategoryRequest $request, $id)
    {
        try {
            $category = Category::query()->where('id', $id)->firstOrFail();
            $category->fill($request->filldata())->save();
            event(new CategoryUpdateEvent());
            return $this->success(__('更新成功'));
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }


    }


    public function delete($id)
    {
        if (Category::query()->where('parent_id', $id)->exists()) {
            return $this->error('该分类下存在子分类，无法删除');
        }

        if (Course::query()->where('category_id', $id)->exists()) {
            return $this->error(__('当前分类下存在课程，无法删除'));
        }
        if (Combo::query()->where('category_id', $id)->exists()) {
            return $this->error(__('当前分类下存在专栏，无法删除'));
        }
        $Category = Category::query()->where('id', $id)->firstOrFail();
        $Category->delete();
        event(new CategoryUpdateEvent());
        return $this->success(__('目录删除成功'));
    }


}
